package com.bs.common.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author bingshao
 * @date 2023/3/17
 **/
public class SnowFlakeUtil {

    private long machineId ;
    private long dataCenterId ;

    /**
     * 初始化构造
     */
    public SnowFlakeUtil(long machineId, long dataCenterId) {
        this.machineId = machineId;
        //分布式部署都为0，会导致主键重复冲突，所以需要根据机器不同产生不同的machineId
        if(this.machineId == 0){
            this.machineId = getMachineId();
        }
        this.dataCenterId = dataCenterId;
        snowflake = IdUtil.getSnowflake(this.machineId,this.dataCenterId);
    }

    /**
     * 初始化构造，无参构造有参函数，默认节点都是0
     */
    public SnowFlakeUtil() {
        this(0L, 0L);
    }

    /**
     * 成员类，SnowFlakeUtil的实例对象的保存域
     */
    private static class IdGenHolder {
        private static final SnowFlakeUtil instance = new SnowFlakeUtil();
    }

    /**
     * 外部调用获取SnowFlakeUtil的实例对象，确保不可变
     */
    public static SnowFlakeUtil get() {
        return IdGenHolder.instance;
    }

    //    private Snowflake snowflake = IdUtil.createSnowflake(machineId, dataCenterId);
    private Snowflake snowflake = null;

    public synchronized long id() {
        return snowflake.nextId();
    }

    public static Long getId() {
        return SnowFlakeUtil.get().id();
    }

    public static Long getMachineId() {
        InetAddress local= null;
        try {
            local = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        if(local == null) {
            return 0L;
        }
        String hostAddress= local.getHostAddress();
        int[] ints = org.apache.commons.lang3.StringUtils.toCodePoints(hostAddress);

        int sums = 0;
        int[] var3 = ints;
        int var4 = ints.length;

        for(int var5 = 0; var5 < var4; ++var5) {
            int b = var3[var5];
            sums += b;
        }

        long workId = (long)(sums % 32);
        return workId;
    }


    public static void main(String[] args){
        System.out.println(getId());
    }
}
